import { Picker } from "@nutui/nutui-react-taro";
import { View } from "@tarojs/components";
import { useMemo, useRef } from "react";
import SelectNode from "../Form/SelectNode";
import Taro from "@tarojs/taro";

type Props = {
  placeholder?: string;
  options?: Option[];
  onChange?: (value: any, text?: any, values?: string[]) => void;
  value?: Option["value"];
  disable?: boolean;
};

export type Option = {
  value: string | number;
  text: string | number;
  children?: Option[];
};

const loop = (option: Option[] = [], value: any): any => {
  for (const item of option) {
    if (item.value === value) {
      return [item];
    }
    let node = loop(item.children || [], value);
    if (node !== undefined) {
      return [item, ...node];
    }

    loop(item.children || [], value);
  }
};

export default (props: Props) => {
  const {
    placeholder = "请选择",
    onChange = () => {},
    options,
    value,
    disable,
  } = props;

  const ref = useRef<any>();

  const levelNode = useMemo(
    () => loop(options || [], value) || [],
    [value, options]
  );

  return (
    <View
      onClick={() => {
        if (disable) return;
        if (!options?.length)
          return Taro.showToast({ title: "暂无可选项", icon: "none" });
        ref.current.open();
      }}
    >
      <SelectNode value={levelNode?.at?.(-1)?.text} placeholder={placeholder} />
      <Picker
        ref={ref}
        value={levelNode.map((item) => item.value)}
        options={options}
        onConfirm={(data) => {
          const { value: v, text: t } = data?.at?.(-1) || {};
          onChange(v, t, data.map((item) => item.value) as any);
          ref.current.close();
        }}
      ></Picker>
    </View>
  );
};
